const http=require('http');
const mysql=require('mysql');
const io=require('socket.io');
const fs=require('fs');
let db=mysql.createPool({host:'localhost',user:'root',password:'root',database:'20181211'});
let httpServer=http.createServer((req,res)=>{   
    fs.readFile(`www${req.url}`,(err,data)=>{
        console.log(data)
        if(err){
            res.writeHead(404);
            res.write('Nodate')
        }else{
            res.write(data)
        }
        res.end();
    })
});
 httpServer.listen(8888);
let wsServer=io.listen(httpServer);
wsServer.on('connection',sock=>{
    sock.on('reg',(user,pass)=>{
        if (!/^\w{6,32}$/.test(user)) {
            sock.emit('reg_ret', '1', '用户名不符合规范')
        } else if (!/^.{6,32}$/.test(pass)) {
            sock.emit('reg_ret', '1', '密码不符合规范')
        } else {
            db.query(`SELECT ID FROM user_table WHERE username='${user}'`,(err,data)=>{
                if(err){
                    console.log(err)
                    sock.emit('reg_ret','1','数据库错误,查询失败')
                }else if(data.length>0){
                    sock.emit('reg_ret','1','用户名已存在')
                }else{
                    db.query(`INSERT INTO user_table (username,password,online) VALUES('${user}','${pass}',0)`,err=>{
                        if(err){
                            console.log(err)
                            sock.emit('reg_ret','1','数据库错误,写入失败')
                        }else{
                            sock.emit('reg_ret','0','注册成功')
                        }
                    });
                }
            })
        }
        // sock.emit('reg_res',0,'登陆成功');
    })
})